package ru.ifmo;

import org.hibernate.Query;
import org.hibernate.Session;

import javax.faces.event.ValueChangeEvent;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

public class LocationSelectBean {
    private String country;
    private String region;
    private String city;
    private Date flightDate;
    private List<String> regionsList = new LinkedList<String>();
    private List<String> citiesList = new LinkedList<String>();
    Session session = HibernateUtil.getSession();


    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getRegion() {
        return region;
    }

    public void setRegion(String region) {
        this.region = region;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public Date getFlightDate() {
        return flightDate;
    }

    public void setFlightDate(Date flightDate) {
        this.flightDate = flightDate;
    }

    public List<String> getCitiesNames() {

        return citiesList;
    }

    public List<String> getRegionNames() {
        return regionsList;
    }

    public void countrySelected(ValueChangeEvent event) {
        regionsList.clear();
        citiesList.clear();
        String selectedCountry = String.valueOf(event.getNewValue());
        Query query = session.getNamedQuery("country.findByName");
        query.setString("name", selectedCountry);

        int selectedCountryId = (Integer) query.uniqueResult();
        Query getRegionsQuery = session.createQuery("select title from RegionsEntity where countryId = :id");
        getRegionsQuery.setInteger("id", selectedCountryId);
        this.regionsList = getRegionsQuery.list();
        Query citiesQuery = session.createQuery("select title from CitiesEntity where countryId = :id");
        citiesQuery.setInteger("id", selectedCountryId);
        this.citiesList = citiesQuery.list();
        this.country = selectedCountry;
    }

    public void regionSelected(ValueChangeEvent event) {
        citiesList.clear();
        String selectedRegion = String.valueOf(event.getNewValue());
        String hql = "select regionId from RegionsEntity where title = :regName";
        Query query = session.createQuery(hql);
        query.setString("regName", selectedRegion);
        int selectedRegionId = (Integer) query.list().get(0);
        Query getCitiesQuery = session.createQuery("select title from CitiesEntity where regionId = :regionId");
        getCitiesQuery.setInteger("regionId", selectedRegionId);
        this.citiesList = getCitiesQuery.list();
        this.region = selectedRegion;
    }
}

